<?php
date_default_timezone_set('Asia/Chongqing');

function saveFromDrag( $filename ){
	$fileInfo = pathinfo($filename);
	$tempPath = getNewUrl( $fileInfo['extension'] );
	$fileContents = file_get_contents("php://input");
	return file_put_contents($tempPath, $fileContents) ? $tempPath : false;
}

//获取图片
function getImage( $url ){
	$newUrl = '';
	$imgContent = '';
	$ext = '(jpg|jpeg|gif|png)';
	$error_code = 0;
	
	if( substr($url,0,10) === 'data:image' ){//base64编码的图片，可能出现在firefox粘贴，或者某些网站上，例如google图片等
		if( preg_match('/^data:image\/'.$ext.'/i', $url, $match) ){
			$imgContent = base64_decode( substr($url,strpos($url,'base64,')+7) );
		}
	} elseif( substr($url,0,5) === 'http:' ) {
	//url图片
		if( preg_match('/\.'.$ext.'$/i', $url, $match) ){
			$imgContent = getUrl($url);
		}
	}else{
	// 上传的临时文件图片
		if( preg_match('/\.'.$ext.'$/i', $url, $match) ){
			$imgContent = file_get_contents($url);
			unlink($url);
		}
	}
	
	$imageSize = strlen($imgContent);
	
	//文件体积不能小于1024，同时不能大于最大限制，默认5M
	if( $imageSize > 1024 && $imageSize <= 2E20*5){
		$newUrl = getNewUrl( $match[1] );
		$newUrl = file_put_contents($newUrl, $imgContent) ? $newUrl : '';
	}
	
	$result = $newUrl ? array(
		'success' => 1,
		'url' => str_replace(JQE_ROOT, '', $newUrl),
		'size' => $imageSize
	): array(
		'error' => $error_code,
		'size' => $imageSize
	);
	
	return $result;
}

function getNewUrl( $ext ){
	$dir = JQE_ROOT.'/upload/'.date('Y');
	!is_dir($dir) && mkdir($dir, 0777) && touch($dir.'/index.htm');
	
	$filename = date("YmdHis").mt_rand(1000,9999).'.'.$ext;
	$newUrl = "$dir/$filename";
	return $newUrl;
}


function formatBytes($bytes) {
	if($bytes >= 1048576) {
		$bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
	} elseif($bytes >= 1024) {
		$bytes = round($bytes / 1024 * 100) / 100 . 'KB';
	} elseif($bytes < 1024) {
		$bytes = $bytes . 'Bytes';
	} else {
		$bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
	}
	return $bytes;
}
